'''
Additions to the OS module.
'''

import errno
import os
import re

try:
    import win32api
except:
    win32api = None

def is_cygwin():
    """Checks if the current platform is Cygwin."""
    if hasattr(os, 'uname'):
        return re.match("cygwin", os.uname()[0], re.I) != None
    else:
        return False

def mkdir_p(path):
    """
    http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
    """
    try:
        os.makedirs(path)
    except OSError, exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        else: raise

class LocalCwd(object):
    """
    A scoped current working directory.  Sample usage:
    
    with LocalCwd("/tmp"):
        # Do stuff in /tmp.
    # Now we're back where we were.
    
    As an added feature, it can work with other os-like interfaces (such as
    one of MEHF's host objects).
    """
    def __init__(self, dir, module=os):
        self.module = module
        self.dir = dir
    
    def __enter__(self):
        self.prev_dir = self.module.getcwd()
        self.module.chdir(self.dir)
        
    def __exit__(self, type, value, traceback):
        self.module.chdir(self.prev_dir)

def get_windows_file_version(path):
    '''
    Gets the file version for a Windows executable or DLL.
    
    Taken from http://mail.python.org/pipermail/python-win32/2006-January/004187.html
    '''
    pairs = win32api.GetFileVersionInfo(path, '\\VarFileInfo\\Translation')
    (lang, codepage) = pairs[0]
    fvi_path = u'\\StringFileInfo\\%04X%04X\\%%s' % (lang, codepage)
    return win32api.GetFileVersionInfo(path, fvi_path % "ProductVersion").encode()

if win32api:
    get_file_version = get_windows_file_version

"""
name_list global variable; an array whose members are analogous to os.name, 
with special handling for Cygwin (which can act as both nt and posix).
"""
name_list = [ os.name ]
if is_cygwin():
    name_list.append('nt')
    
    # The Cygwin docs recommend against this, but it's the easiest way to have
    # the rest of the code work transparently whether it's being run from 
    # Cygwin or Python for Windows.  For more details:
    # http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
    # (TODO? Actually, much of the code won't work from Cygwin at all...)
    os.environ['nodosfilewarning'] = '1'
